package tech.aistar.service.impl.daoyouService;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import com.sun.javafx.collections.MappingChange;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.data.redis.core.RedisOperations;
import org.springframework.data.redis.core.RedisTemplate;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tech.aistar.entity.authordis.UserTable;
import tech.aistar.entity.daoyou.*;
import tech.aistar.entity.daoyou.GuideBills.GetGuideBill;
import tech.aistar.entity.daoyou.GuideBills.GuideSetBillTime;
import tech.aistar.entity.daoyou.GuideBills.GuideSetBills;
import tech.aistar.entity.person_center.Orders;
import tech.aistar.mapper.guidemapper.Guide;
import tech.aistar.mapper.guidemapper.GuideHome;
import tech.aistar.mapper.guidemapper.GuideTimemapper;
import tech.aistar.service.daoyou.GuideService;
import tech.aistar.util.RedisUtil;
import tech.aistar.util.SmsModel;
import tech.aistar.util.date_SimpleDateFormat.DateUtileDemo;
import tech.aistar.vo.daoyou.GuideIndex;
import tech.aistar.vo.daoyou.GuideOrdersAll;
import tech.aistar.vo.daoyou.MyOrders;


import java.sql.Date;

import java.text.SimpleDateFormat;
import java.util.*;

@Service
@Transactional
public class daoyouServiceImpl implements GuideService {

    @Autowired
    private Guide guide;
    @Autowired
    private GuideHome guideHome;
    //导入redis
    @Autowired
    private RedisTemplate redisTemplate;

    //单例
     private GuideSetBills getGuideBills=GetGuideBill.getInstance();

    //分页
    @Override
    public PageInfo<GuidePageCommen> GuideCommentPage(Integer PageNum, Integer PageSize,Integer id) {
        PageHelper.startPage(PageNum,PageSize);
        List<GuidePageCommen> list=guide.getGuideCommen(id);
        Iterator<GuidePageCommen> iterator=list.iterator();

        while (iterator.hasNext()){
            GuidePageCommen c=iterator.next();

//            Date time = c.getContentsTime();
//            String t=DateUtileDemo.format("yyyy-MM-dd HH:mm:ss",time);
            String t=DateUtileDemo.format("yyyy-MM-dd",c.getContentsTime());
            c.setTimes(t);      ;
        }

        PageInfo<GuidePageCommen> pageInfo=new PageInfo<>(list);
        return pageInfo;
    }


    @Override
    public Map<String, Object> getallPersons(Integer pageNum, Integer pageSize) {
        Set<GuideIndex> guideIndices= new HashSet<>();
        PageHelper.startPage(pageNum,pageSize);
        List<GuideInfo> persons=guide.getAllPerson();//获取所有的导游的信息
        PageInfo<GuideInfo> guideInfoPageInfo=new PageInfo<>(persons);
        Iterator<GuideInfo> infoIterator=persons.iterator();
        while (infoIterator.hasNext()){
            GuideInfo guideInfo=infoIterator.next();
            GuideIndex guideIndex=new GuideIndex(); //新建一个Vo中的类 包含界面的信息
            List<GuideLaber> laber =guide.getLaber(guideInfo.getId()); //获取这个人的所有的标签
            GuideAllLaber guideLabers=  new GuideAllLaber();
            Iterator<GuideLaber> laberIterator=laber.iterator();
            List<GuideAllLaber> labers=new ArrayList<>();//标签
            while (laberIterator.hasNext()){
                Integer   guideLaber=laberIterator.next().getLable();//
                GuideAllLaber guideAllLaber=    new GuideAllLaber();
                guideAllLaber.setPlaber(guide.getLaberById(guideLaber));
                labers.add(guideAllLaber);
            }
            guideIndex.setGuideLaber(labers);//获取这个人的所有的标签
            guideIndex.setGuideInfo(guideInfo); //将导游详情表的信息保存
            GuideApply guideApply= guide.getByObj(guideInfo);
            guideIndex.setGuideApply(guideApply);
            guideIndices.add(guideIndex);
        }
        Map<String,Object> maps = new HashMap<>();
        maps.put("guideInfoPageInfo",guideInfoPageInfo);
        maps.put("guideIndices",guideIndices);
        return maps;
    }


    @Override
    public Set<GuideIndex> getAllPerson() {

        Set<GuideIndex> guideIndices= new HashSet<>();
        List<GuideInfo> persons=guide.getAllPerson();//获取所有的导游的信息
        Iterator<GuideInfo> infoIterator=persons.iterator();
        while (infoIterator.hasNext()){
            GuideInfo guideInfo=infoIterator.next();
            GuideIndex guideIndex=new GuideIndex(); //新建一个Vo中的类 包含界面的信息
            List<GuideLaber> laber =guide.getLaber(guideInfo.getId()); //获取这个人的所有的标签
            GuideAllLaber guideLabers=  new GuideAllLaber();
             Iterator<GuideLaber> laberIterator=laber.iterator();
            List<GuideAllLaber> labers=new ArrayList<>();//标签
             while (laberIterator.hasNext()){
                 Integer   guideLaber=laberIterator.next().getLable();//
                 GuideAllLaber guideAllLaber=    new GuideAllLaber();
                 guideAllLaber.setPlaber(guide.getLaberById(guideLaber));
                 labers.add(guideAllLaber);
             }
            guideIndex.setGuideLaber(labers);//获取这个人的所有的标签
            guideIndex.setGuideInfo(guideInfo); //将导游详情表的信息保存
            GuideApply guideApply= guide.getByObj(guideInfo);
            guideIndex.setGuideApply(guideApply);
            guideIndices.add(guideIndex);
          }


        return guideIndices;
    }



    @Override
    public UserTable getuserByGuideId(Integer id) {
        GuideInfo guideInfo= guide.getPersonById(id);

        GuideApply  guideApply=guide.getByObj(guideInfo);

        UserTable userTable= guide.getImg( guideApply.getUserId());

        return userTable;
    }


    @Override
    public GuideIndex getPerosonById(Integer id) {
        GuideIndex guideIndex=new GuideIndex(); //新建一个Vo中的类 包含界面的信息

        //从redis中取出 判读是否为空
        String ids= String.valueOf(id);
        Object o= redisTemplate.opsForValue().get("t"+ids);

        if(o==null){
            //未null从数据库中找出
            GuidePraise guidePraise=   guide.getPrais(id);
            if(guidePraise==null){
                //如果数据库为空 则说明并没有数据 需要创建
                guide.addPraise(id);//新建数据库数据的数据
                redisTemplate.opsForValue().set("t"+ids,0);
                guideIndex.setPraise("0");
            }else{
                redisTemplate.opsForValue().set("t"+ids,guidePraise.getNum());
                guideIndex.setPraise(String.valueOf(guidePraise.getNum()));
            }
        }else{
            guideIndex.setPraise(String.valueOf(o));
        }

        GuideInfo p=  guide.getPersonById(id);//获取所有的导游的信息

        List<GuideLaber> laber =guide.getLaber(p.getId()); //获取这个人的所有的标签
        GuideAllLaber guideLabers=  new GuideAllLaber();
        Iterator<GuideLaber> laberIterator=laber.iterator();
        List<GuideAllLaber> labers=new ArrayList<>();//标签
        while (laberIterator.hasNext()){
            Integer   guideLaber=laberIterator.next().getLable();//
            GuideAllLaber guideAllLaber=    new GuideAllLaber();
            guideAllLaber.setPlaber(guide.getLaberById(guideLaber));
            labers.add(guideAllLaber);
        }
        guideIndex.setGuideLaber(labers);//获取这个人的所有的标签
        //获取导游的照片
        List<GuidePhoto> list= guide.getGuidePhotoById(id);
        guideIndex.setPhotos(list);

        guideIndex.setGuideInfo(p); //将导游详情表的信息保存
        GuideApply guideApply= guide.getByObj(p);
        //设置地区
        String address=guideApply.getCurrentAddress().split("省")[1].split("市")[0].toString();
        guideApply.setCurrentAddress(address);
        guideIndex.setGuideApply(guideApply);

        return guideIndex;
    }

    @Override
    public Boolean getOrderById(Integer id, String  play_name,Date endtime) {

        /**
         * 刚开始的时候如果内存没有要查的导游无数据
         * 必须要从数据库中找出先插入
         */
        if(getGuideBills.getHashMapTime()==null ||(getGuideBills.getHashMapTime().get(id)==null) ){
            ArrayList<GuideSetBillTime> times= new ArrayList<>();
            HashMap<Integer,ArrayList<GuideSetBillTime>> hashMap=new HashMap<>();
            List<Orders> orders=guide.getALlbill(id);//获取这个导游所有的账单
            System.out.println("导游的所有账单");
            orders.forEach(System.out::print);
            Iterator<Orders> ordersIterator=orders.iterator();
            while (ordersIterator.hasNext()){ //赋值

                Orders orderso=  ordersIterator.next();

                String startTime=DateUtileDemo.format("yyyy-MM-dd",orderso.getApplyTime());
                String endTime=DateUtileDemo.format("yyyy-MM-dd",orderso.getPlayDay());

                GuideSetBillTime guide = new GuideSetBillTime(startTime,endTime);
                times.add(guide);
            }
            //将这个导游的所有信息全部放入
            hashMap.put(id,times);
            getGuideBills.setHashMapTime(hashMap); //将数据插入
        }

        Boolean Flags=false;

        GuideSetBillTime checkGuide = new GuideSetBillTime(play_name,DateUtileDemo.format("yyyy-MM-dd",endtime)); //测试
        //开始检测
        HashMap<Integer, ArrayList<GuideSetBillTime>> hashMap1=getGuideBills.getHashMapTime();
        Set<Map.Entry<Integer, ArrayList<GuideSetBillTime>>> l=hashMap1.entrySet();
        Iterator<Map.Entry<Integer, ArrayList<GuideSetBillTime>>> a=l.iterator();

        while (a.hasNext()){

            Map.Entry<Integer, ArrayList<GuideSetBillTime>> d=a.next();
            //导游id
            if(d.getKey()==id){
                ArrayList<GuideSetBillTime> times1=d.getValue();
                Collections.sort(times1);
                System.out.println("排序");
                System.out.println(times1.size());
                times1.forEach(System.out::print);
                if(times1.size()==0){
                    Flags=true;
                    break;
                }

                if(times1.get(0).getStarttime().compareTo(checkGuide.getEndtime())>0){
                    System.out.println("直接排在第一位");
                    times1.add(checkGuide);
                    Flags=true;
                    break;
                }
                if(times1.get(times1.size()-1).getEndtime().compareTo(checkGuide.getEndtime())<0){
                    System.out.println("直接排在最后一位");
                    times1.add(checkGuide);
                    Flags=true;
                    break;
                }
                Iterator<GuideSetBillTime> iterator=times1.iterator();
                GuideSetBillTime flag=null;
                while (iterator.hasNext()){
                    GuideSetBillTime g=iterator.next();

                    if(g.getStarttime().compareTo(checkGuide.getStarttime())<0){
                        flag=g;
                    }
                    if(g.getStarttime().compareTo(checkGuide.getStarttime())==0){
                        break;
                    }
                    if(g.getStarttime().compareTo(checkGuide.getStarttime())>0){
                        if( (flag.getEndtime().compareTo(checkGuide.getStarttime())<0 )&&(g.getStarttime().compareTo(checkGuide.getEndtime())>0) ){
                            System.out.println("插入成功");
                            times1.add(checkGuide);
                            Flags=true;
                            break;
                        }
                    }
                }
            }
        }
        getGuideBills.getHashMapTime().remove(id);

//        java.sql.Date sqlapplyTime= java.sql.Date.valueOf(play_name);
//        Orders orders=   guide.getOrderById(id,sqlapplyTime,endtime);
        return Flags;
    }

    @Override
    public void inserOrders(MyOrders myOrders) {
        guide.inserOrders(myOrders);
    }


    @Override
    //此用户id
    public List<GuideOrdersAll> getBill(Integer id, String apply_time) {
        List<Orders>  bill= guideHome.getBill(id,apply_time);
        Iterator<Orders> iterator=bill.iterator();
        List<GuideOrdersAll> guideOrdersAlls=new ArrayList<>();
       while (iterator.hasNext()){
           GuideOrdersAll ordersAll= new GuideOrdersAll();
           Orders o=iterator.next();
           String sex= guideHome.getUserById(o.getUserId());
           String d= DateUtileDemo.format("yyyy-MM-dd",o.getApplyTime());
           ordersAll.setOrders(o);
           ordersAll.setSex(sex);
           ordersAll.setStartTime(d);
           guideOrdersAlls.add(ordersAll);
       }
        return guideOrdersAlls;
    }


    @Override
    public GuideInfo SelectGuideById(Integer id) {
        GuideApply apply=  guideHome.SelectGuideById(id);
        GuideInfo guideInfo=null;
        return apply==null?guideInfo:guideHome.getGuideInfo(apply.getId());
    }

    @Override
    public Orders getBillById(Integer id) {
        return  guideHome.getBillById(id);
    }

    //检查下单
    @Override
    //
    public Orders checkOrder(Integer id,Integer uid){


        Orders  orders= guideHome.getOrdersById(id);
        guideHome.checkOrder(orders);
        return null;
    }

    @Override
    public void accessBill(Integer id) {
        guideHome.accessBill(id);
    }

    @Override
    public void delBill(Integer id) {
        guideHome.delBill(id);
    }

    @Override
    public List<GuideOrdersAll> getAllBill(Integer id) {
        List<Orders> orders= guideHome.getAllBill(id);

        Iterator<Orders> iterator=orders.iterator();
        List<GuideOrdersAll> guideOrdersAlls=new ArrayList<>();
        while (iterator.hasNext()){
            GuideOrdersAll ordersAll= new GuideOrdersAll();
            Orders o=iterator.next();
            String sex= guideHome.getUserById(o.getUserId());
            String d= DateUtileDemo.format("yyyy-MM-dd",o.getApplyTime());
            ordersAll.setOrders(o);
            ordersAll.setSex(sex);
            ordersAll.setStartTime(d);
            guideOrdersAlls.add(ordersAll);
        }
        return guideOrdersAlls;
    }

    //
    @Override
    public GuideInfo checkApply(Integer id) {
       GuideApply apply= guide.getApplyById(id); //
        GuideInfo info=null;
        return apply==null?info:guide.getGuideInfoId(apply.getId());
    }

    //路线的更改和创建
    @Override
    public void guideRout(Integer id, String text) {
        GuideRoute route=guideHome.getAllRoutById(id);
        if(route==null){
            guideHome.inserRout(id,text);
        }else{
            guideHome.gupdateRoutById(id,text);
        }
    }

    @Override
    public GuideRoute selectRouteByid(Integer id) {
        GuideRoute route=guideHome.getAllRoutById(id);
        return route;
    }

    @Override
    public GuideInfo getGuideById(Integer id) {
        GuideInfo guideInfo=guide.getPersonById(id);
        return guideInfo;
    }

    @Override
    public void setGuideById(Integer id, Integer val) {

        guideHome.setGuideState(id,val);


    }

    //取消订单
    @Override
    public void setOrders(Integer id,Integer guideid) {
        guideHome.setOrders(id);//取消订单
        //短信通知
        //积分减少
        guideHome.setGuideScore(guideid);

    }

    @Autowired
    GuideTimemapper guideTimemapper;
    //定时任务
    @Override
    public void getNoAcctionOrder() {
       List<Orders> orders=guide.getNoAcctionOrder();
       Iterator<Orders> iterator=orders.iterator();
        java.util.Date date = new java.util.Date();
       while (iterator.hasNext()){
         Orders orders1= iterator.next();


         //订单过期
         if(orders1.getOrderStatus()==0 &&  orders1.getApplyTime().getDay()<= date.getDay()){
             System.out.println(orders1.getId() +"id");

             guideTimemapper.updateOrder(orders1.getId());
         }
         //订单完成过期
         if(orders1.getOrderStatus()==1 && orders1.getPlayDay().getDay()<= date.getDay()){
             guideTimemapper.delOrder(orders1.getId());
         }
       }

    }



//点赞
    @Override
    public String addPRAISE(Integer id,String ip) {

        String  ids= String.valueOf(id);
        long InserState=redisTemplate.opsForSet().add(ids, ip);
      if((int)InserState==1){
         redisTemplate.opsForValue().increment("t"+ids,1);
        Object o= redisTemplate.opsForValue().get("t"+ids);
          return  o.toString();
      }else{
        return  "no";
      }

    }

//将redis中保存的值取出 保存在mysql
    @Override
    public void delRedis() {
        Set<String> objects = redisTemplate.keys("t*"); //获取每个人的点赞数

        for (String key : objects) {
        String keys= key.split("t")[1];
          Integer num= (Integer) redisTemplate.opsForValue().get(key);
          Integer id=Integer.valueOf(keys);
          guideTimemapper.addPraise(num,id);
          redisTemplate.delete(keys);
        }
         redisTemplate.delete(objects);
    }

    @Override
    public Integer getPhoneNum(Integer id) {

        return  guide.getPhoneNum(id);
    }

    //插入图片
    @Override
    public void inserPhoto(Integer id, String imgs) {
       if(guide.getPhoneNum(id)==4){
           return;
       }else{
           String[] photos=imgs.split(",");
           for(String p:photos){
               if(p!=null&&p.length()>0)
                   guide.inserPhoto(id,p);
           }

       }

    }

    //短信通知用户
    @Override
    public void Notice() {
        java.util.Date date = new java.util.Date();//获取今天
        Calendar c = Calendar.getInstance();
        c.setTime(date);
        c.add(Calendar.DAY_OF_MONTH, 1);// 今天+1天
        java.util.Date  tomorrow =  c.getTime();
        String strDateFormat = "yyyy-MM-dd ";
        String d= DateUtileDemo.format(strDateFormat,tomorrow);
        List<Orders> orders=guideTimemapper.getGo(d);
        Iterator<Orders> iterator=orders.iterator();
        while (iterator.hasNext()){

            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            Orders orders1= iterator.next();
           String phone=orders1.getPhoneNumber();
            SmsModel.sendSms(phone,441561,orders1.getApplyName());

        }
    }

    /**
     * @Description:检查订单
     * @param:
     * @author XiaoDi
     * @date 2019/10/18 9:30
    */
    @Override
    public Boolean checkUserBill(Integer id,String starttime) {
        List<Orders> list=guide.checkUserBill(id);
        Iterator<Orders> iterator=list.iterator();
        while (iterator.hasNext()){
            Orders orders=iterator.next();
            String actionTime=DateUtileDemo.format("yyyy-MM-dd",orders.getApplyTime());
            if(actionTime.equals(starttime)){
                return false;
            }
        }
        return true;
    }
}
